package org.example.springboot.controller;

import org.example.springboot.common.Result;
import org.example.springboot.entity.Teach;
import org.example.springboot.service.TeachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teach")
public class TeachController {

    @Autowired
    private TeachService teachService;

    @GetMapping("/page")
    public Result getTeachPage(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String course,
            @RequestParam int pageNum,
            @RequestParam int pageSize) {

        List<Teach> teaches;
        int totalCount;

        if (name != null && course != null) {
            // 根据名称和课程进行分页查询
            teaches = teachService.findByNameAndCourse(name, course, pageNum, pageSize);
            totalCount = teachService.countByNameAndCourse(name, course);
        } else if (name != null) {
            // 仅根据名称进行分页查询
            teaches = teachService.findByName(name, pageNum, pageSize);
            totalCount = teachService.countByName(name);
        } else if (course != null) {
            // 仅根据课程进行分页查询
            teaches = teachService.findByCourse(course, pageNum, pageSize);
            totalCount = teachService.countByCourse(course);
        } else {
            return Result.error("输入不能都唯为空");
        }

        // 构建返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("list", teaches);
        response.put("total", totalCount);

        return Result.success(response);
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(teachService.findByTeacherAndCourse());
    }

    @GetMapping("/selectByAccount")
    public Result selectByAccount(@RequestParam String account) {
        return Result.success(teachService.findByAccount(account));
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Teach teach) {
        teachService.insertTeach(teach);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable int id) {
        teachService.deleteTeach(id);
        return Result.success();
    }

}
